Ext.BLANK_IMAGE_URL='/wsd/image/page/s.gif';
Ext.onReady(function(){
	var parent_id = 0;//默认类别为父类别
	var parent_level = 0;
	var c_node = null;
	var categoryTree = new Ext.tree.TreePanel({
		title:'商品类别',
		region:'west',
		frame:true,
		width:200,
		split:true,
		collapsible:true,
		rootVisible : false,
		autoScroll : true,
		root:new Ext.tree.AsyncTreeNode({
			id : '0',
			text : '类别'
		}),
		loader: new Ext.tree.TreeLoader({
			url:'/wsd/admin/category_categoryTreeData.action'
    	})
	});
	categoryTree.expandAll();

	var keyField = new Ext.form.TextField({
		name:'key',
		fieldLabel:'关键字'
	})
	var searchBtn = new Ext.Button({
		text:'搜索',
		handler:search
	})
	var searchPanel = new Ext.Panel({
		region:'north',
		layout:'column',
		height:40,
		frame:true,
		items:[
			{
				layout:'form',
				items:[keyField]
			},
			{
				layout:'form',
				items:[searchBtn]
			}
		]
	})
	var sm = new Ext.grid.CheckboxSelectionModel();
	var cm = new Ext.grid.ColumnModel([
		sm,
		{header:'商品编号',dataIndex:'PId'},
		{header:'商品名称',dataIndex:'PName'},
		{header:'商品类别',dataIndex:'CName'},
		{header:'商品型号',dataIndex:'model'},
		{header:'条形码',dataIndex:'barcode'},
		{header:'价格',dataIndex:'showPrice'},
		{header:'厂商',dataIndex:'factory'},
		{header:'图片',dataIndex:'image',renderer:function(value){
			var src = '/wsd/image/product/' + value;
			return '<a href =' + src + ' target="_blank"><img width="40" height="40" src="' + src + '"/></a>';
		}},
		{header:'评论',dataIndex:'comments',renderer:function(value,m,record,ri,ci){
			
			
			if(value == 0){
				return '暂无评论';
			}else{
				var pid = record.get('PId');
				//alert(pid);
				return '<a href="/wsd/admin/product_comments.action?pid=' + pid +'" target="_blank">' + value + '条评论</a>';
			}
			
		}}
	])
	
	var productStore = new Ext.data.JsonStore({
		url:'/wsd/admin/product_search.action',
		totalProperty:'result.total',
		root:'result.products',
		autoLoad:true,
		baseParams:{
			'category.CId':0,
			start:0,
			limit:10
		},
		fields:['PId','PName',
			{name:'CName',mapping:'category.CName'},
			
			{name:'comments',mapping:'productCommentsCount'},
			'model','barcode','factory','image','showPrice','priceMap','category']
	})
	
	var productsPanel = new Ext.grid.GridPanel({
		region:'center',
		store:productStore,
		viewConfig:{
			forceFit:true
		},
		loadMask:true,
		autoScroll:true,
		cm:cm,
		sm:sm,
		bbar:new Ext.PagingToolbar({
			pageSize:10,
			store:productStore,
			displayInfo:true,
			displayMsg:'显示第 {0} 条到 {1} 条记录，一共 {2} 条',
			emptyMsg:'没有记录'
		}),
		tbar:new Ext.Toolbar([
			{
				text:'修改查看',
				handler:function(){
					var records = sm.getSelections();
					//var record = productsPanel.getSelectionModel().getSelected();
					//var product = record.data;
					if(records.length == 0){
						Ext.Msg.alert('系统信息','请先选择商品');
						return false;
					}
					
					createModifyWindow(records[0].data);
				
				}
			},
			{
				text:'推荐',
				handler:function(){
					var records = sm.getSelections();
					var len = records.length;
					if(records.length == 0){
						Ext.Msg.alert('系统信息','请先选择商品');
						return false;
					}
					createRankWindow(records);
				
				}
			},
			'->',
			{
				text:'删除',
				handler:function(){
					//var record = productsPanel.getSelectionModel().getSelected();
					var records = sm.getSelections();
					//var product = record.data;
					var len = records.length;
					if(records.length == 0){
						Ext.Msg.alert('系统信息','请先选择商品');
						return false;
					}
					Ext.Msg.confirm('系统信息','你确定要删除这' + len + '条记录',function(btn){
						if(btn == 'yes'){
							delProduct(records);
						}
					});
				}
			}
		])
	})
	
	//中间主面板
	var panel = new Ext.Panel({
		region:'center',
		layout:'border',
		items:[searchPanel,productsPanel]
	})
	
	
	var viewport = new Ext.Viewport({
		layout : 'border',
		frame:true,
		items : [categoryTree,panel]
	});
	productsPanel.on('rowdblclick',function(grid,rowIndex,e){
		//openOrderListWindow()
		var product = productsPanel.getStore().getRange()[rowIndex].data;
		createModifyWindow(product);
		
	})
	categoryTree.on("click",function(node,e){
		/*parent_id = node.attributes.id;
		parent_level = node.attributes.level;
		categoryField.setValue(node.attributes.text);*/
		//productStore.reload()
		productStore.baseParams['category.CId'] = node.attributes.id;
		productStore.load({
			params:{
				start:0,
				limit:10
			}
		})
	})
	/**
	 * 创建修改查看窗口
	 */
	function createModifyWindow(product){
		
		var categoryName = new Ext.form.Label({
			fieldLabel:'类别',
			allowBlank:false,
			name:'category.CName',
			text:product.CName
			
		})
		var productNameField = new Ext.form.TextField({
			fieldLabel:'商品名称(*)',
			allowBlank:false,
			blankText:'商品名称不能为空',
			msgTarget:'under',
			width:200,
			name:'product.PName',
			value:product.PName
		})
		
		var barcodeField = new Ext.form.TextField({
			fieldLabel:'条形码(*)',
			allowBlank:false,
			blankText:'条形码不能为空',
			msgTarget:'under',
			width:200,
			name:'product.barcode',
			value:product.barcode
		})
		var modelField = new Ext.form.TextField({
			fieldLabel:'型号(*)',
			allowBlank:false,
			blankText:'型号不能为空',
			msgTarget:'under',
			name:'product.model',
			value:product.model
		})
		var factoryField = new Ext.form.TextField({
			fieldLabel:'厂商',
			width:200,
			name:'product.factory',
			value:product.factory
		})
		
		var descriptionArea = new Ext.form.HtmlEditor({
			fieldLabel:'描述',
			width:400,
			height:100,
			name:'product.description',
			value:product.description
		})
		var categoryField = new Ext.form.Hidden({
			name:'product.category.CId',
			value:product.category.CID
		})
		var productIdField = new Ext.form.Hidden({
			name:'product.PId',
			value:product.PId
		})
		var fileuploadField = new Ext.form.TextField({
			name : 'upload',
			// allowBlank:false,
			blankText : '图片不能为空',
			msgTarget : 'under',
			id : 'upload_form',
			width : 400,
			// emptyText: '请选择图片文件',
			fieldLabel : '图片(*)',
			buttonText : '',
			buttonCfg : {
				iconCls : 'upload-icon'
			},
			inputType: 'file'
		})
		var userField1 = new Ext.form.NumberField({
			width:50,
			allowBlank:false,
			blankText:'普通会员价格不能为空',
			msgTarget:'under',
			name:'price1.price',
			fieldLabel:'普通会员',
			value:product.priceMap[1]
			
		})
		var userField2 = new Ext.form.NumberField({
			name:'price2.price',
			width:50,
			fieldLabel:'高级会员',
			value:product.priceMap[2]
		})
		var userField3 = new Ext.form.NumberField({
			width:50,
			name:'price3.price',
			fieldLabel:'VIP会员',
			value:product.priceMap[3]
		})
		userField1.on('blur',function(field){
			var price = field.getValue();
			userField2.setValue(price);
			userField3.setValue(price);
		});
		var pricePanel = new Ext.Panel({
			fieldLabel:'价格',
			layout:'column',
			items:[
				{
					columnWidth:.3,
					layout:'form',
					items:[userField1]
				},
				{
					columnWidth:.3,
					layout:'form',
					items:[userField2]
				},
				{
					columnWidth:.3,
					layout:'form',
					items:[userField3]
				}
			]
		})
		var modifyBtn = new Ext.Button({
			text:'修改',
			handler:function(){
				if(!validateFile(Ext.getCmp('upload_form').getValue())){
		    		return false;
		    	}
				if(form.getForm().isValid()){
         		  form.getForm().submit({
	            	url:'admin/product_update.action',
	                waitMsg: '系统正在处理，请稍后……',
	                success: function(fp, o){
	                	productStore.reload();
	                	Ext.Msg.alert('系统信息',"修改成功");
	                	//addBtn.setDisabled(true);
	                	//resetBtn.setText('继续添加');
	                	
	                	
	                },
	                failure:function(fp, o){
	                	Ext.Msg.alert('系统信息',o.result.msg);
	                }
	            });
        }
			}
		})
		var extiBtn = new Ext.Button({
			text:'退出',
			handler:function(){
				productWin.close();

			}
		
		})
		var form = new Ext.form.FormPanel({
			region:'center',
			frame:'true',
			fileUpload:true,
			items:[categoryName,productNameField,barcodeField,modelField,factoryField,fileuploadField
//			    {
//	            xtype: 'fileuploadfield',
//	            name:'upload',
//	            //allowBlank:false,
//	            blankText:'图片不能为空',
//				msgTarget:'under',
//	            id: 'upload_form',
//	            width:400,
//	            //emptyText: '请选择图片文件',
//	            fieldLabel: '图片(*)',
//	            buttonText: '',
//	            buttonCfg: {
//	                iconCls: 'upload-icon'
//	            }
//	        }
			,pricePanel,descriptionArea,productIdField
			],
			buttons: [modifyBtn,extiBtn]
		})
	
		var productWin = new Ext.Window({
			title:product.PName + ' 的信息',
			layout:'border',
			width:680,
			height:400,
			maximizable:true,
			modal:true,
			constrain:true,//防止窗口超出边界,
			items:[form]
			
		})
		productWin.show();
	}
	/**
	 * 删除一条记录
	 */
	function delProduct(records){
		var ids = new Array();
		var len = records.length;
		for(var i = 0; i < len; i++){
			ids.push(records[i].data.PId)
		}
		Ext.Msg.wait("正在删除……");
		Ext.Ajax.request({
			url:'/wsd/admin/product_delete.action',
			params:{
				'ids':ids
			},
			success:function(response){
				productStore.reload();
				Ext.Msg.hide();
				Ext.Msg.alert('系统信息','删除成功');
			},
			failure:function(){
				Ext.Msg.hide();
				Ext.Msg.alert('系统信息','删除失败');
			}
		
		});
	}
	function validateFile(file){
		if(file == '' || file == null){
			//Ext.Msg.alert('系统信息','请选择文件');
			return true;
		}
		var req = /(.jpg|.jpeg|.bmp|.png|.gif)$/;
		var result = req.exec(file);
		if(result == null){
			Ext.Msg.alert('系统信息','文件格式错误，请上传图片文件!');
			return false;
		}
		return true;
	}
	function search(){
		var key = keyField.getValue();
		if(key == null || key == ''){
			Ext.Msg.alert('系统信息','搜索内容不能为空');
			return false;
		}
		productStore.load({
			params:{
				search:true,
				key:key,
				start:0,
				limit:10
			}
		})
	}
	/**
	 * 创建推荐页面
	 */
	function createRankWindow(records){
		var ids = new Array();
		var len = records.length;
		for(var i = 0; i < len; i++){
			ids.push(records[i].data.PId)
		}
		var rankCombo = new Ext.form.ComboBox({
			fieldLabel:'加入榜单',
			mode:'local',
			name:'text',
			triggerAction:'all',
			valueField:'model',
			displayField:'bName',
			value:1,
			editable:false,
			store:new Ext.data.SimpleStore({
				fields:['model','bName'],
				data:[
					['1','特价商品'],
					['2','热卖榜单'],
					['3','新品榜单']
				]
			})
		})
		var saveBtn = new Ext.Button({
			text:'保存',
			handler:function(){
				var model = rankCombo.getValue();
				form.getForm().submit({
					url:'/wsd/admin/product_saveRank.action',
					params:{
						ids:ids,
						model:model
					},
					success: function(fp, o){
	                	//productStore.reload();
	                	Ext.Msg.alert('系统信息',"修改成功");
	                },
	                failure:function(fp, o){
	                	Ext.Msg.alert('系统信息',o.result.msg);
	                }
				})
			}
		})
		var exitBtn = new Ext.Button({
			text:'退出',
			handler:function(){
				rankWindow.close();
			}
		})
		var form = new Ext.FormPanel({
			region:'center',
			frame:true,
			items:[rankCombo],
			buttons:[saveBtn,exitBtn]
		})
		var rankWindow = new Ext.Window({
			title:'推荐窗口',
			layout:'border',
			width:300,
            height:100,
			modal:true,
			constrain:true,//防止窗口超出边界,
			items:[form]
		})
		rankWindow.show();
		
		
	}
});